<template>
  <div class="main">
    <div class="init" v-show="!onScan">
      <input placeholder="请输入地址  例如http://www.baidu.com/ " v-model="url" />
      <textarea placeholder="请输入敏感字段 ',' 分割  例如 name,no 忽略大小写" v-model="words" style="margin-top:10px"></textarea>

      <div class="user-words">
        <div style="text-align: left;margin-top: 10px;color: #777;margin-bottom: 4px;">常见敏感词
          <div class="botton" style="margin: 0px;display: inline-block;margin-left: 10px;font-size: 0.8rem;" @click="choiceAll">全选</div>
        </div>
        <div @click="choiceWord(item)" class="item" v-for="(item,index) in useWords">{{item}}</div>
      </div>

      <div class="botton" @click="start()">开始</div>
      <div class="history" v-if="history.length>0">
        <div>最近使用</div>
        <div @click="toStart(item)" v-for="(item,index) in history" class="item">
          {{item.url}}
        </div>
      </div>
    </div>

    <div class="resust" v-if="onScan">
      <div class="top-title">
        <div class="title">{{url}}</div>
        <div class="botton" @click="report()">导出报告</div>
        <div class="botton" @click="stop()">退出</div>
      </div>
      <div class="content">
        <div class="scan-url">
          <div class="pass">
            <div class="title-1">已过滤的安全地址</div>
            <div class="list">
              <div class="item" v-for="(item,index) in passUrls">
                {{item}}
              </div>
            </div>
          </div>
          <div class="worr">
            <div class="title-1">已过滤的敏感地址</div>
            <div class="list">
              <div @click="showWorr(index)" :class="{'active':index == showWorrIndex}" class="item" v-for="(item,index) in worrUrls">
                {{item.url}}
              </div>
            </div>
          </div>
        </div>

        <div class="worr-detail">
          <div class="title-1">敏感信息内容</div>
          <div class="text" contentEditable='true' v-html="worrDetail.rsp"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { globalBus } from "@/assets/js/globalBus.js";
import axios from 'axios';
var ipcRenderer;
if (window.require) {
  ipcRenderer = window.require('electron').ipcRenderer;
}
export default {
  name: "",
  components: {},
  data() {
    return {
      onScan: false,
      showWorrIndex: -1,
      history: [],
      words: '',
      url: '',
      worrDetail: { rsp: '', url: '' },
      passUrls: [],
      worrUrls: [],
      urlSet: new Set(),
      matchTest: '',
      webUrl: '',
      useWords: ["no", "loginNo", "mail", "employeeNo", "wechatId", "phone", "telephone", "phoneNumber", "wechatName", "idCard", "address", "postalAddress"]
    };
  },
  watch: {},
  created() {

  },
  mounted() {
    let h = window.sessionStorage.getItem("san-history")
    if (h) {
      this.history = JSON.parse(h)
    }
    //监听窗口变化
    if (ipcRenderer) {
      ipcRenderer.on("onBeforeSendHeaders", (event, data) => {
        if (this.urlSet.has(data.url.split('?')[0])) {
          return
        }
        this.urlSet.add(data.url.split('?')[0])

        if (data.url.indexOf(this.url) < 0) {
          return
        }
        if (data.requestHeaders.fromTag) {
          return
        }
        if (data.resourceType == 'xhr') {
          console.log(data)
          axios.get(data.url,
            {
              headers: { 'fromTag': 'awork' }
            }).then(
              response => {
                let resjson = JSON.stringify(response)
                let warr = this.matchTest.test(resjson.toLowerCase())
                if (warr) {
                  this.worrUrls.unshift({
                    url: data.url,
                    rsp: resjson,
                    webUrl: this.webUrl
                  })
                } else {
                  this.passUrls.unshift(data.url)
                }
              }
            ).catch(
              response => {
                console.log(response)
              },
            );
        }
      });

      ipcRenderer.on("scan-main-url-refresh-to", (event, data) => {
        this.webUrl = data
      })
    }
  },
  methods: {
    choiceWord(word) {
      if (this.words.indexOf(word) >= 0) return
      if (this.words.lastIndexOf(',') != this.words.length - 1) {
        this.words += ','
      }
      this.words += word
    },
    choiceAll() {
      for (let i = 0; i < this.useWords.length; i++) {
        if (this.words.indexOf(this.useWords[i]) >= 0) continue
        this.words += this.useWords[i]
        if (i != this.useWords.length - 1) {
          this.words += ','
        }
      }
    },
    showWorr(index) {
      var jsonObj = JSON.parse(this.worrUrls[index].rsp) //把json字符串转为json对象
      let rsp = JSON.stringify(jsonObj, null, 4);
      let json = ''
      let arr = rsp.split('\n')
      for (let i in arr) {
        let item = arr[i].replace(/\s/g, '&nbsp;');
        let warr = this.matchTest.test(item.toLowerCase())
        let color = warr ? 'red' : '#7f8c8d'
        json += "<div><font color='" + color + "'>" + item + "</font></div>";
      }
      this.worrDetail.rsp = json
    },
    report() {
      let report = '## 敏感字段检测结果\n\n'
      for (let i in this.worrUrls) {
        let wsSet = new Set()
        report += "### 接口:" + this.worrUrls[i].url + "\n\n"
        report += "所属页面：" + this.worrUrls[i].webUrl + "\n\n"
        report += "类型：get\n\n"
        var jsonObj = JSON.parse(this.worrUrls[i].rsp) //把json字符串转为json对象
        report += "敏感字段：\n"
        let formatJson = JSON.stringify(jsonObj, null, 4)
        let ws = formatJson.toLowerCase().match(this.matchTest)
        let lasWs = ws[ws.length - 1];
        for (let i in ws) {
          let x = ws[i].replace(/\s+/g, '').split(":")[0]
          x = x.replace(/\"/g, '')
          if (!wsSet.has(x)) {
            wsSet.add(x)
            report += x + '  '
          }
        }
        report += '\n\n'

        let subIndex = formatJson.toLowerCase().indexOf(lasWs) + lasWs.length + 10

        report += "原数据：\n```json\n" + formatJson.substring(0, subIndex) + "...\n```\n\r\n\r\n\r"
    
      }

      console.log(report)
      this.exportRaw(
        "敏感字段检测结果.md",
        report
      );
    },
    exportRaw(name, data) {
      var urlObject = window.URL || window.webkitURL || window;
      var export_blob = new Blob([data]);
      var save_link = document.createElementNS(
        "http://www.w3.org/1999/xhtml",
        "a"
      );
      save_link.href = urlObject.createObjectURL(export_blob);
      save_link.download = name;
      this.fakeClick(save_link);
    },
    fakeClick(obj) {
      var ev = document.createEvent("MouseEvents");
      ev.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      obj.dispatchEvent(ev);
    },
    stop() {
      this.onScan = false
      this.showWorrIndex = -1
      this.worrDetail = { rsp: '', url: '' }
      this.passUrls = []
      this.worrUrls = []
      this.urlSet = new Set()
      this.matchTest = ''
      this.webUrl = ''
      if (ipcRenderer) {
        ipcRenderer.send("close-scan-window");
      }
    },
    toStart(data) {
      if (data.url) {
        this.url = data.url
      }
      if (data.words) {
        this.words = data.words
      }
    },
    start() {
      if (!this.url || !this.words) {
        return
      }
      if (this.url.indexOf("http") < 0) {
        this.url = "http://" + this.url
      }
      if (this.url.lastIndexOf("/") == this.url.length - 1) {
        this.url = this.url.substring(0, this.url.length - 1)
      }

      this.history.unshift({ url: this.url, words: this.words })
      if (this.history.length > 10) {
        this.history = this.history.slice(0, 10)
      }
      window.sessionStorage.setItem("san-history", JSON.stringify(this.history))

      this.onScan = true

      let ws = this.words.split(",")
      let wstest = '/.*'
      for (let i = 0; i < ws.length; i++) {
        wstest += '"' + ws[i] + '":'
        if (i != ws.length - 1) {
          wstest += '|'
        }
      }
      wstest += '.*/g'
      wstest = wstest.toLowerCase()
      this.matchTest = eval(wstest)
      if (ipcRenderer) {
        ipcRenderer.send("open-scan-window", this.url);
      }
    },
  }
};
</script>

<style lang="less" scoped>
.main {
  user-select: text;
  box-sizing: border-box;
  padding: 10px;
  padding-top: 0;
  width: 100%;
  height: 100%;
  .init {
    width: 400px;
    margin: 0 auto;
    text-align: center;
    margin: 40px auto;
    input {
      border: 1px #bdc3c7 solid;
      border-radius: 4px;
      outline: none;
      width: 100%;
      padding: 4px 10px;
      box-sizing: border-box;
    }
    textarea {
      border: 1px #bdc3c7 solid;
      border-radius: 4px;
      outline: none;
      width: 100%;
      padding: 4px 10px;
      box-sizing: border-box;
      min-height: 3rem;
      resize: vertical;
      max-height: 10rem;
    }
    .user-words {
      .item {
        display: inline-flex;
        padding: 4px 10px;
        cursor: pointer;
        border-radius: 4px;
      }
      .item:hover {
        background: #eeeeee;
      }
    }
  }
  .history {
    width: 100%;
    color: #7f8c8d;
    text-align: left;
    margin-top: 40px;
    .item {
      cursor: pointer;
      transition: all 0.2s linear;
      margin: 4px 0;
      border-radius: 4px;
      padding: 4px 10px;
    }
    .item:hover {
      background: #eeeeee;
    }
  }
  .botton {
    display: table;
    margin: 0px auto;
    padding: 4px 20px;
    border-radius: 4px;
    background: #3498db;
    color: #fff;
    cursor: pointer;
    margin-top: 40px;
  }
  .botton:hover {
    background: #2980b9;
  }

  .resust {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    .top-title {
      display: flex;
      box-sizing: border-box;
      padding: 10px;
      box-shadow: 0 0px 6px rgba(200, 200, 200, 0.1);
      background: #fff;
      border-radius: 6px;
      .title {
        line-height: 29px;
        color: #34495e;
        flex: 1;
        font-weight: bold;
      }
      .botton {
        margin: 0;
        margin-left: 10px;
      }
    }

    .top-title:hover {
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    .content {
      flex: 1;
      height: 100%;
      margin-top: 10px;
      overflow: hidden;
      box-sizing: border-box;
      display: flex;
      .scan-url {
        max-width: 30%;
        height: 100%;
        margin-right: 5px;
        flex: 1;
        box-sizing: border-box;
        padding: 10px;
        box-shadow: 0 0px 6px rgba(200, 200, 200, 0.1);
        background: #fff;
        border-radius: 6px;
        display: flex;
        flex-direction: column;
        .title-1 {
          margin-bottom: 10px;
          color: #34495e;
        }
        .pass {
          box-sizing: border-box;
          flex: 1;
          height: 10px;
          overflow: hidden;
          .item {
            font-size: 0.8rem;
            padding: 4px;
            color: #1abc9c;
          }
          .list {
            height: 90%;
            overflow: auto;
          }
        }
        .worr {
          box-sizing: border-box;
          height: 10px;
          overflow: hidden;
          flex: 1;
          .item {
            cursor: pointer;
            font-size: 0.8rem;
            padding: 4px;
            color: #d35400;
          }
          .item:hover {
            background: #eeeeee;
          }

          .item.active {
            background: #eeeeee;
          }
          .list {
            height: 90%;
            overflow: auto;
          }
        }
      }
      .worr-detail {
        width: 10px;
        height: 100%;
        margin-left: 5px;
        box-sizing: border-box;
        padding: 10px;
        box-shadow: 0 0px 6px rgba(200, 200, 200, 0.1);
        background: #fff;
        border-radius: 6px;
        flex: 2;
        display: flex;
        flex-direction: column;
        .text {
          overflow: auto;
          padding-top: 10px;
          color: #7f8c8d;
          flex: 1;
          width: 100%;
          height: 100%;
          resize: none;
          border: none;
          outline: none;
        }
      }
      .worr-detail:hover,
      .scan-url:hover {
        box-shadow: 0 0 6px rgba(0, 0, 0, 0.1);
      }
    }
  }
}
</style>
